package com.site.common;

import com.site.pojo.User;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 *  把每个用户的信息与请求存在不同的进程中
 */
public class RequestHolder {

    // 用户进程，把每个用户的信息存在不同的进程中
    private static final ThreadLocal<User> userHolder = new ThreadLocal<>();

    // 用户进程，把每个用户的请求存在不同的进程中
    private static final ThreadLocal<HttpServletRequest> requestHolder = new ThreadLocal<>();

    // 线程安全时间
    private static final ThreadLocal<SimpleDateFormat> dateFormatHolder = ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
    /* 等价于上面的 ，  initialValue 方法返回当前线程的初始值
    private static final ThreadLocal<SimpleDateFormat> dateFormatHolder = new ThreadLocal<>(){
        @Override
        protected Object initialValue() {
            return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        }
    };*/

    public static void add(User user){
        userHolder.set(user);
    }

    public static void add(HttpServletRequest request){
        requestHolder.set(request);
    }

    public static User getCurrentUser(){
        return userHolder.get();
    }

    public static HttpServletRequest getCurrentRequest(){
        return requestHolder.get();
    }

    public static SimpleDateFormat getDateFormat(){
        return dateFormatHolder.get();
    }

    // 进程关闭时移除
    public static void remove(){
        userHolder.remove();
        requestHolder.remove();
        dateFormatHolder.remove();
    }
}
